package com.hzu.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

public class JsonUtil {
	/**
	 * 返回JSON数据
	 * @param response
	 * @param obj
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	public static void write(HttpServletResponse response, Object obj) throws JsonProcessingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException, JsonProcessingException {
				arg1.writeString("");

			}
		});
		response.getWriter().write(mapper.writeValueAsString(obj));
	}
	/**
	 * 格式化JSON
	 * @param obj
	 * @return
	 */
	public static String getJson(Object obj){
		try {
		ObjectMapper mapper = new ObjectMapper();
		mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException, JsonProcessingException {
				arg1.writeString("");

			}
		});
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}
}
